package org.alvin.switchserver;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

import java.beans.PropertyChangeSupport;
import java.net.InetSocketAddress;

/**
 * 接收到的报文
 */
public class PrintInputNettyMegHandler extends ChannelInboundHandlerAdapter {

    private final PropertyChangeSupport uiEventBus ;

    public PrintInputNettyMegHandler(PropertyChangeSupport uiEventBus) {
        this.uiEventBus = uiEventBus;
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            if (msg instanceof ByteBuf) {
                ByteBuf data = (ByteBuf) msg;
                ByteBuf frame = data.retainedDuplicate();
                InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();

                byte[] databyte = new byte[data.readableBytes()];
                data.readBytes(databyte);
                //界面打印
                this.uiEventBus.firePropertyChange("inputNettyMessage",false, ByteBufUtil.hexDump(databyte));
                ctx.fireChannelRead(frame);
            }
        } finally {
            ReferenceCountUtil.release(msg);
        }


    }
    }